﻿using Apps.IDAL;
using Dapper;
using Heima.OA.IBLL;
using Heima.OA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Heima.OA.BLL
{
    public partial class ZS_DeclareInfoService : BaseService<ZS_DeclareInfo>
    {
        /// <summary>
        /// 添加共同申报人数据
        /// </summary>
        /// <param name="declareId"></param>
        /// <param name="jointIds"></param>
        /// <returns></returns>
        public bool AddDeclareJointApplicant(int declareId, string[] memberIds)
        {
            //List<ZS_JointApplicant> jointList = new List<ZS_JointApplicant>();
            //添加申报表的共同申报人数据 先删除申报表关联的共同申报人数据 在重新添加
            var jointList = DbSession.ZS_JointApplicantDal.GetEntities(u => u.DelFlag == 0 && u.DeclareId == declareId).AsEnumerable();
            foreach(var joint in jointList)
            {
                joint.DelFlag = 1;
                DbSession.ZS_JointApplicantDal.Update(joint);
            }
            foreach (var memberId in memberIds)
            {
                ZS_JointApplicant joint = new ZS_JointApplicant();
                joint.MemberId = Convert.ToInt32(memberId);
                joint.DeclareId = declareId;
                joint.DelFlag = 0;
                joint.CreateTime = DateTime.Now;
                DbSession.ZS_JointApplicantDal.Add(joint);
            }
            return DbSession.SaveChanges() > 0;
        }
        /// <summary>
        /// 更新关联的房号的  DeclareId 字段 废弃
        /// </summary>
        /// <param name="declareId"></param>
        /// <param name="houseIds"></param>
        /// <returns></returns>
        public bool UpdateDeclareHouse(int declareId, string[] houseIds)
        {
            //List<ZS_HouseInfo> houseList = new List<ZS_HouseInfo>();
            //先取消与申报表关联的房屋  房屋重新添加关联
            var houseList = DbSession.ZS_HouseInfoDal.GetEntities(h => h.DelFlag == 0 && h.DeclareId == declareId);
            foreach(var house in houseList)
            {
                house.DeclareId = 0;
                DbSession.ZS_HouseInfoDal.Update(house);
            }
            foreach (var id in houseIds)
            {
                ZS_HouseInfo house = DbSession.ZS_HouseInfoDal.GetModel(Convert.ToInt32(id));
                if (house != null)
                {
                    house.DeclareId = declareId;
                    DbSession.ZS_HouseInfoDal.Update(house);
                }
            }
            return DbSession.SaveChanges() > 0;
        }
        /// <summary>
        /// 添加或更新 申报的 房屋信息
        /// </summary>
        /// <param name="declareId"></param>
        /// <param name="buildingId"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public bool AddDeclareHouse(int declareId, int buildingId, List<ZS_HouseInfo> houseList)
        {
            foreach(var item in houseList)
            {
                if (item.Id > 0)
                {
                    ZS_HouseInfo houseModel = DbSession.ZS_HouseInfoDal.GetModel(item.Id);
                    houseModel.BuildingId = buildingId;
                    houseModel.HouseName = item.HouseName;
                    houseModel.HouseArea = item.HouseArea;
                    houseModel.DecorationSituation = item.DecorationSituation;
                    houseModel.ActualityUse = item.ActualityUse;
                    houseModel.Remark = item.Remark;
                    DbSession.ZS_HouseInfoDal.Update(houseModel);
                }
                else
                {
                    item.DeclareId = declareId;
                    item.BuildingId = buildingId;
                    item.CreateTime = DateTime.Now;
                    item.DelFlag = 0;
                    DbSession.ZS_HouseInfoDal.Add(item);
                }
            }
            return DbSession.SaveChanges()>0;
        }
        /// <summary>
        /// 多表分页查询
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="total"></param>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public IEnumerable<DeclareView> GetPageEntities(int pageSize, int pageIndex, out int total, string where, string order)
        {
            total = 0;
            string oldwhere = where;
            where = !string.IsNullOrEmpty(where) ? " where " + where : "";
            string sql = string.Format(@" with oa as (
	                select ROW_NUMBER() over (order by Id) as num,*
	                from ZS_DeclareInfo {0}
                ),
                ob as (
	                select * from oa
	                where num between  {1} and {2}
                ),
                oc as (
	                select ob.*,c.RegisterNumber,d.BuildingName from ob
	                left join ZS_FamilyInfo as c on ob.FamilyId=c.Id
	                left join ZS_BuildingInfo as d on  ob.BuildingId=d.Id
                )
                select * from oc ", where, (pageIndex - 1) * pageSize + 1, pageIndex * pageSize);
            IEnumerable<DeclareView> viewList = DapperHelper.GetAppMall.Query<DeclareView>(sql);
            total = GetCount(oldwhere);
            return viewList;
        }
        public int GetCount(string where)
        {
            where = !string.IsNullOrEmpty(where) ? " where " + where : "";
            string sql = string.Format(@"
                    select COUNT(1) from ZS_DeclareInfo
                     {0} ", where);
            int count = (int)DapperHelper.GetAppMall.ExecuteScalar(sql);
            return count;
        }
        /// <summary>
        /// 获取编辑数据
        /// </summary>
        /// <param name="declareModel"></param>
        /// <returns></returns>
        public object GetEditModel(ZS_DeclareInfo declareModel)
        {
            object obj = new object();
            List<ZS_JointApplicant> jointList = DbSession.ZS_JointApplicantDal.GetEntities(u => u.DelFlag == 0 && u.DeclareId == declareModel.Id).AsQueryable().ToList();
            string memberIds = string.Empty;
            if (jointList.Count > 0)
            {
                jointList.ForEach(u => memberIds += u.MemberId + ",");
                memberIds = memberIds.TrimEnd(',');
            }
            List<ZS_HouseInfo> houseList = DbSession.ZS_HouseInfoDal.GetEntities(u => u.DelFlag == 0 && u.DeclareId == declareModel.Id).AsQueryable().ToList();
            obj = new
            {
                DeclareInfo = declareModel,
                MemberIds = memberIds,
                HouseList = houseList
            };
            return obj;
        }

        #region 申报转核查
        public bool DeclareTransferCheck()
        {
            //转移申报数据到核查
            FamilyTransfer();
            MemberTransfer();
            SetFamily();
            BuildingTransfer();
            HouseTransfer();
            //建立核查阶段家庭与当事人关系  楼栋与房号关系
            SetCheckMember();
            SetCheckHouse();

            return true;
        }
        private int FamilyTransfer()
        {
            List<ZS_FamilyInfo> familyList = DbSession.ZS_FamilyInfoDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var family in familyList)
            {
                ZS_CheckFamilyInfo checkFamilyInfo = new ZS_CheckFamilyInfo();
                checkFamilyInfo.DeclareFamilyId = family.Id;
                checkFamilyInfo.FamilyCode = family.FamilyCode;
                checkFamilyInfo.SpouseMemberId = 0;
                checkFamilyInfo.SpouseMemberName = string.Empty;
                checkFamilyInfo.HuBie = family.HuBie;
                checkFamilyInfo.PowerMemberName = string.Empty;
                checkFamilyInfo.PowerMemberId = 0;
                checkFamilyInfo.FamilyAddress = family.FamilyAddress;
                checkFamilyInfo.RegisterNumber = family.RegisterNumber;
                checkFamilyInfo.DelFlag = family.DelFlag;
                checkFamilyInfo.CreateTime = DateTime.Now;
                DbSession.ZS_CheckFamilyInfoDal.Add(checkFamilyInfo);
            }
            return DbSession.SaveChanges();
        }
        private int MemberTransfer()
        {
            List<ZS_Member> memberList = DbSession.ZS_MemberDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var member in memberList)
            {
                ZS_CheckMember checkMember = new ZS_CheckMember();
                checkMember.DeclareMemberId = member.Id;
                checkMember.CheckFamilyId = 0;
                checkMember.MemberName = member.MemberName;
                checkMember.WithPowerRelation = member.WithPowerRelation;
                checkMember.Sex = member.Sex;
                checkMember.MaritalStatus = member.MaritalStatus;
                checkMember.Birthday = member.Birthday;
                checkMember.IDNumber = member.IDNumber;
                checkMember.IdentityType = member.IdentityType;
                checkMember.RegisterInfo = member.RegisterInfo;
                checkMember.Mobile = member.Mobile;
                checkMember.MoveIntoTime = member.MoveIntoTime;
                checkMember.DelFlag = member.DelFlag;
                checkMember.CreateTime = DateTime.Now;
                checkMember.DeclareFamilyId = member.FamilyId;
                DbSession.ZS_CheckMemberDal.Add(checkMember);
            }
            return DbSession.SaveChanges();
        }
        /// <summary>
        /// 设置核查家庭户主
        /// </summary>
        /// <returns></returns>
        private int SetFamily()
        {
            List<ZS_CheckFamilyInfo> checkFamilyList = DbSession.ZS_CheckFamilyInfoDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach(var item in checkFamilyList)
            {
                ZS_FamilyInfo family = DbSession.ZS_FamilyInfoDal.GetModel((int)item.DeclareFamilyId);
                if (family != null)
                {
                    ZS_CheckMember checkMember = DbSession.ZS_CheckMemberDal.GetEntities(u => u.DelFlag == 0 && u.DeclareMemberId == family.PowerMemberId).FirstOrDefault();
                    if(checkMember != null)
                    {
                        item.PowerMemberId = checkMember.Id;
                        item.PowerMemberName = checkMember.MemberName;
                        DbSession.ZS_CheckFamilyInfoDal.Update(item);
                    }
                }
            }
            return DbSession.SaveChanges();
        }

        private int BuildingTransfer()
        {
            List<ZS_BuildingInfo> buildingList = DbSession.ZS_BuildingInfoDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var building in buildingList)
            {
                ZS_CheckBuildingInfo checkBuildingInfo = new ZS_CheckBuildingInfo();
                checkBuildingInfo.DeclareBuildingId = building.Id;
                checkBuildingInfo.BuildingCode = building.BuildingCode;
                checkBuildingInfo.BuildingName = building.BuildingName;
                checkBuildingInfo.Location = building.Location;
                checkBuildingInfo.Floors = building.Floors;
                checkBuildingInfo.BuildingStructure = building.BuildingStructure;
                checkBuildingInfo.HouseUse = building.HouseUse;
                checkBuildingInfo.ActualityUse = building.ActualityUse;
                checkBuildingInfo.StructureArea = building.StructureArea;
                checkBuildingInfo.MappingArea = building.MappingArea;
                checkBuildingInfo.CompriseArea = building.CompriseArea;
                checkBuildingInfo.JiDiArea = building.JiDiArea;
                checkBuildingInfo.PropertyRight = building.PropertyRight;
                checkBuildingInfo.BuiltTime = building.BuiltTime;
                checkBuildingInfo.IsObtainNoncommodityRightCertificate = building.IsObtainNoncommodityRightCertificate;
                checkBuildingInfo.ObtainedCertificateName = building.ObtainedCertificateName;
                checkBuildingInfo.CertificateCode = building.CertificateCode;
                checkBuildingInfo.CetificateArea = building.CetificateArea;
                checkBuildingInfo.NoObtainCertificateBuiltArea = building.NoObtainCertificateBuiltArea;
                checkBuildingInfo.Remark = building.Remark;
                checkBuildingInfo.DelFlag = building.DelFlag;
                checkBuildingInfo.CreateTime = DateTime.Now;
                DbSession.ZS_CheckBuildingInfoDal.Add(checkBuildingInfo);
            }
            return DbSession.SaveChanges();
        }
        private int HouseTransfer()
        {
            List<ZS_HouseInfo> houseList = DbSession.ZS_HouseInfoDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var house in houseList)
            {
                ZS_CheckHouseInfo checkHouseInfo = new ZS_CheckHouseInfo();
                checkHouseInfo.DeclareHouseId = house.Id;
                checkHouseInfo.CheckBuildingId = 0;
                checkHouseInfo.HouseName = house.HouseName;
                checkHouseInfo.HouseArea = house.HouseArea;
                checkHouseInfo.DecorationSituation = house.DecorationSituation;
                checkHouseInfo.ActualityUse = house.ActualityUse;
                checkHouseInfo.Remark = house.Remark;
                checkHouseInfo.DelFlag = house.DelFlag;
                checkHouseInfo.CreateTime = DateTime.Now;
                checkHouseInfo.CheckId = 0;
                checkHouseInfo.CerName = string.Empty;
                checkHouseInfo.CerCode = string.Empty;
                checkHouseInfo.RegisterRight = string.Empty;
                checkHouseInfo.RegisterBuildingArea = 0;
                checkHouseInfo.ContractSigner = string.Empty;
                checkHouseInfo.ContractRegisterBuildingArea = 0;
                checkHouseInfo.AttachmentId = 0;
                checkHouseInfo.BuildingCode = string.Empty;
                checkHouseInfo.ViolationOriginCode = string.Empty;
                checkHouseInfo.IsBuiltBeforeDate = 0;
                checkHouseInfo.BuiltAreaBeforeDate = 0;
                checkHouseInfo.BuiltAreaAfterDate = 0;
                checkHouseInfo.ViolationBuiltArea = 0;
                checkHouseInfo.DeclareBuildingId = house.BuildingId;
                DbSession.ZS_CheckHouseInfoDal.Add(checkHouseInfo);
            }
            return DbSession.SaveChanges();
        }
        private int SetCheckMember()
        {
            List<ZS_CheckMember> checkMembers = DbSession.ZS_CheckMemberDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var member in checkMembers)
            {
                ZS_CheckFamilyInfo checkFamily = DbSession.ZS_CheckFamilyInfoDal.GetEntities(u => u.DelFlag == 0 && u.DeclareFamilyId == member.DeclareFamilyId).FirstOrDefault();
                if (checkFamily != null)
                {
                    member.CheckFamilyId = checkFamily.Id;
                    DbSession.ZS_CheckMemberDal.Update(member);
                }
            }
            return DbSession.SaveChanges();
        }
        private int SetCheckHouse()
        {
            List<ZS_CheckHouseInfo> checkHouseInfos = DbSession.ZS_CheckHouseInfoDal.GetEntities(u => u.DelFlag == 0).ToList();
            foreach (var house in checkHouseInfos)
            {
                ZS_CheckBuildingInfo checkBuilding = DbSession.ZS_CheckBuildingInfoDal.GetEntities(u => u.DelFlag == 0 && u.DeclareBuildingId == house.DeclareBuildingId).FirstOrDefault();
                if (checkBuilding != null)
                {
                    house.CheckBuildingId = checkBuilding.Id;
                    DbSession.ZS_CheckHouseInfoDal.Update(house);
                }
            }
            return DbSession.SaveChanges();
        }
        #endregion
        #region 根据楼栋统计申报信息
        public object BuildingDeclareInfo(int id)
        {
            ZS_BuildingInfo buildingInfo = DbSession.ZS_BuildingInfoDal.GetModel(id);
            List<int> declareMemberList = new List<int>();
            decimal totalHouseArea = 0;
            if (buildingInfo != null)
            {
                //获取楼栋 申报权利人与共同申报人 去重
                var declareList = DbSession.ZS_DeclareInfoDal.GetEntities(u => u.DelFlag == 0 && u.BuildingId == id).ToList();
                //申报表个数
                int declareCount = declareList.Count;
                foreach(var item in declareList)
                {
                    if(!declareMemberList.Exists(u=> u== item.MemberId))
                    {
                        declareMemberList.Add((int)item.MemberId);
                    }
                    var jointList = DbSession.ZS_JointApplicantDal.GetEntities(u => u.DelFlag == 0 && u.DeclareId == item.Id).ToList();
                    foreach(var joint in jointList)
                    {
                        if (!declareMemberList.Exists(u => u == joint.MemberId))
                        {
                            declareMemberList.Add((int)item.MemberId);
                        }
                    }
                }
                int declareMemberCount = declareMemberList.Count;
                //已申报总面积
                var houseList = DbSession.ZS_HouseInfoDal.GetEntities(u => u.DelFlag == 0 && u.BuildingId == buildingInfo.Id);
                totalHouseArea += (int)houseList.Sum(u => u.HouseArea);
                object obj = new
                {
                    buildingInfo,
                    declareCount,
                    declareMemberCount,
                    totalHouseArea,
                    houseList
                };
                return obj;
            }
            else
            {
                return null;
            }
        }
        #endregion

    }
}
